﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace Directory.Web
{
    public partial class Admin_Category : System.Web.UI.Page
    {
        protected string categoryIdKey = "categoryId";
        protected int categoryId = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.RegularExpressionValidator1.ErrorMessage = Resources.Resource.ResourceManager.GetString("NANMSG");
            ltMsg.Text = "";
            string action;
            action = Request.QueryString["action"];
            if (action == null)
            {
                Response.End();
            }
            if (!IsPostBack)
            {
                if (!int.TryParse(Request.QueryString[categoryIdKey], out categoryId))
                {
                    categoryId = -999;
                }
                this.btnDelete.Attributes.Add("onclick", "return(confirm('确认要删除该目录吗？'))");
                switch (action.Trim().ToLower())
                {
                    case "addrootcategory":
                    case "addchilds":
                        RendAddChilds();
                        break;
                    case "delete":
                        DeleteCategory();
                        break;
                    case "modify":
                        RendModify();
                        break;
                    case "batchadd":
                        RendBatchAdd();
                        break;
                    case "batchdelete":
                        BatchDeleteCategory();
                        break;
                    case "setorder":
                        SaveOrder();
                        break;
                    default:
                        break;
                }
            }
        }

        private void BatchDeleteCategory()
        {
            string idlist = Request.QueryString["idlist"];
            string[] idarr = idlist.Split(new char[] { ',' });
            int catId;
            string failId = string.Empty;
            int count = 0;
            foreach (string id in idarr)
            {
                if (int.TryParse(id, out catId))
                {
                    if (CategoryDataProxy.DeleteCategory(catId))
                    {
                        count++;
                    }
                }
            }
            ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('成功删除" + count.ToString() + "项。');Go2Category(" + Request.QueryString[categoryIdKey] + ",false);</script>");
        }

        private void DeleteCategory()
        {
            if (int.TryParse(Request.QueryString[categoryIdKey], out categoryId))
            {
                Directory.Model.CategoryInfo cat = CategoryDataProxy.GetCategory(categoryId);
                if (cat == null)
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>location.replace(location.href);</script>");
                }
                if (CategoryDataProxy.DeleteCategory(categoryId))
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('删除成功。');Go2Category(" + cat.ParentCategoryId + ",true);</script>");
                }
                else
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('删除失败。只能删除空目录。');</script>");
                }
            }
        }

        private void RendAddChilds()
        {
            this.pnlSingle.Visible = true;

            IList<Directory.Model.CategoryInfo> catList = new List<Directory.Model.CategoryInfo>();
            if (Request.QueryString["action"] == "addrootcategory")
            {
                this.ltTittle.Text = "<b style='color:red;'>添加根" + Resources.Resource.Category + "</b>";
                this.pnlRootAdd.Visible = true;
                catList.Add(CategoryDataProxy.GetCategory(WebSettings.GetInstance().RootCategoryId));
            }
            else if (Request.QueryString["action"] == "addchilds")
            {
                this.ltTittle.Text = "<b style='color:red;'>添加" + Resources.Resource.Category + "</b>";
                this.pnlSingleAdd.Visible = true;
                if (Request.QueryString[categoryIdKey].Trim() == WebSettings.GetInstance().RootCategoryId.ToString())
                {
                    catList.Add(CategoryDataProxy.GetCategory(WebSettings.GetInstance().RootCategoryId));
                }
                else
                {
                    catList = CategoryDataProxy.GetRootCategoriesForUser(Page.User.Identity.Name);
                    IList<Directory.Model.CategoryInfo> parentPath = CategoryDataProxy.GetRecursiveParentsOfCategory(int.Parse(Request.QueryString[categoryIdKey]));
                    string pathStr = null;
                    foreach (Directory.Model.CategoryInfo cat in parentPath)
                    {
                        pathStr += cat.CategoryId.ToString() + ",";
                    }
                    if (pathStr != null)
                    {
                        CascadingCategory.SelectedIndexStr = pathStr.Remove(pathStr.Length - 1);
                        CascadingCategory.AutoLoad = true;
                    }
                }
            }
            CascadingCategory.DataSource = catList;
            CascadingCategory.DataBind();
        }

        private void RendModify()
        {
            this.pnlSingle.Visible = true;
            this.ltTittle.Text = "<b style='color:red;'>编辑" + Resources.Resource.Category + "</b>";

            this.pnlModify.Visible = true;
            if (int.TryParse(Request[categoryIdKey], out categoryId))
            {
                Directory.Model.CategoryInfo cat = CategoryDataProxy.GetCategory(categoryId);
                if (cat != null)
                {
                    tbName.Text = cat.CategoryName;
                    tbDescription.Text = cat.Description;
                    tbMarker.Text = cat.Marker;
                    tbOrder.Text = cat.Order.ToString();

                    IList<Directory.Model.CategoryInfo> catList = new List<Directory.Model.CategoryInfo>();
                    if (cat.ParentCategoryId == WebSettings.GetInstance().RootCategoryId)
                    {
                        catList.Add(CategoryDataProxy.GetCategory(WebSettings.GetInstance().RootCategoryId));
                        CascadingCategory.AutoLoad = true;
                        CascadingCategory.SelectedIndexStr = WebSettings.GetInstance().RootCategoryId.ToString();
                    }
                    else
                    {
                        IList<Directory.Model.CategoryInfo> parentPath = CategoryDataProxy.GetRecursiveParentsOfCategory(cat.ParentCategoryId);
                        if (RoleDataProxy.IsUserInRole(Page.User.Identity.Name, WebSettings.GetInstance().RootCategoryAdminRole))
                        {
                            Directory.Model.CategoryInfo rootCategory = CategoryDataProxy.GetCategory(WebSettings.GetInstance().RootCategoryId);
                            catList.Add(rootCategory);
                            parentPath.Insert(0, rootCategory);
                        }
                        else
                        {
                            catList = CategoryDataProxy.GetRootCategoriesForUser(Page.User.Identity.Name);
                        }
                        string pathStr = null;
                        foreach (Directory.Model.CategoryInfo ct in parentPath)
                        {
                            pathStr += ct.CategoryId.ToString() + ",";
                        }
                        if (pathStr != null)
                        {
                            CascadingCategory.SelectedIndexStr = pathStr.Remove(pathStr.Length - 1);
                            CascadingCategory.AutoLoad = true;
                        }
                    }
                    CascadingCategory.DataSource = catList;
                    CascadingCategory.DataBind();
                }
            }
        }

        private void RendBatchAdd()
        {
            this.pnlBatch.Visible = true;
            this.ltTittle.Text = "<b style='color:red;'>批量添加" + Resources.Resource.Category + "</b>";

            IList<Directory.Model.CategoryInfo> catList = new List<Directory.Model.CategoryInfo>();
            if (Request.QueryString[categoryIdKey].Trim() == WebSettings.GetInstance().RootCategoryId.ToString())
            {
                catList.Add(CategoryDataProxy.GetCategory(WebSettings.GetInstance().RootCategoryId));
            }
            else
            {
                catList = CategoryDataProxy.GetRootCategoriesForUser(Page.User.Identity.Name);
                IList<Directory.Model.CategoryInfo> parentPath = CategoryDataProxy.GetRecursiveParentsOfCategory(int.Parse(Request.QueryString[categoryIdKey]));
                string pathStr = null;
                foreach (Directory.Model.CategoryInfo cat in parentPath)
                {
                    pathStr += cat.CategoryId.ToString() + ",";
                }
                if (pathStr != null)
                {
                    CascadingCategory_batch.SelectedIndexStr = pathStr.Remove(pathStr.Length - 1);
                    CascadingCategory_batch.AutoLoad = true;
                }
            }
            CascadingCategory_batch.DataSource = catList;
            CascadingCategory_batch.DataBind();
        }

        //设置排序
        protected void SaveOrder()
        {
            Response.Clear();
            string msg = "设置成功";
            string ids = Request.QueryString["ids"];
            if (string.IsNullOrEmpty(ids))
            {
                return;
            }
            string[] vals = ids.Split('|');

            for (int i = 0; i < vals.Length; i++)
            {
                int order = i + 1;
                int id = Convert.ToInt32(vals[i]);
                Model.CategoryInfo cat = CategoryDataProxy.GetCategory(id);
                if (cat == null)
                {
                    continue;
                }
                if (cat.Order == order)
                {
                    continue;
                }
                cat.Order = order;
                Model.CategoryInfo.ErrorCode err;
                CategoryDataProxy.UpdateCategoryInfo(cat, out err);
                if (err != Model.CategoryInfo.ErrorCode.Success)
                {
                    msg = "设置失败";
                    break;
                }
            }
            Response.Write(msg);
            Response.End();
        }

        // 添加目录
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Directory.Model.CategoryInfo.ErrorCode errorCode;
            int order;
            if (!int.TryParse(tbOrder.Text, out order))
            {
                order = 0;
            }
            Directory.Model.CategoryInfo cat = null;
            try
            {
                cat = CategoryDataProxy.CreateCategory(tbName.Text, CascadingCategory.SelectedId, tbDescription.Text, tbMarker.Text, order, out errorCode);
            }
            catch (Exception ex)
            {
                ltMsg.Text = "添加失败，服务器错误：" + ex.Message;
                return;
            }
            switch (errorCode)
            {
                case Directory.Model.CategoryInfo.ErrorCode.Success:
                    ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('添加成功。');Go2Category(" + CascadingCategory.SelectedId + ",false);</script>");
                    break;
                case Directory.Model.CategoryInfo.ErrorCode.InvalidName:
                    ltMsg.Text = "添加失败，目录名不可用（为空或存在同名目录）。";
                    break;
                case Directory.Model.CategoryInfo.ErrorCode.InvalidParentCategory:
                    ltMsg.Text = "添加失败，父目录不可用。";
                    break;
                default:
                    ltMsg.Text = "添加失败，未知错误。";
                    break;
            }
        }

        // 保存修改
        protected void btnSave_Click(object sender, EventArgs e)
        {
            int categoryId;
            if (int.TryParse(Request[categoryIdKey], out categoryId))
            {
                Directory.Model.CategoryInfo cat = CategoryDataProxy.GetCategory(categoryId);
                if (cat == null)
                {
                    ltMsg.Text = "保存失败：该目录已经被删除。";
                    return;
                }
                cat.ParentCategoryId = CascadingCategory.SelectedId;
                cat.CategoryName = tbName.Text;
                cat.Marker = tbMarker.Text;
                cat.Order = int.Parse(tbOrder.Text);

                Directory.Model.CategoryInfo.ErrorCode errorCode = new Directory.Model.CategoryInfo.ErrorCode();
                try
                {
                    CategoryDataProxy.UpdateCategoryInfo(cat, out errorCode);
                }
                catch (Exception ex)
                {
                    ltMsg.Text = "服务器错误：" + ex.Message;
                }
                switch (errorCode)
                {
                    case Directory.Model.CategoryInfo.ErrorCode.Success:
                        ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('保存成功。');Go2Category(" + cat.CategoryId + ",false);</script>");
                        break;
                    case Directory.Model.CategoryInfo.ErrorCode.InvalidName:
                        ltMsg.Text = "保存失败：目录名不可用（为空或已存在同名目录）。";
                        break;
                    case Directory.Model.CategoryInfo.ErrorCode.InvalidParentCategory:
                        ltMsg.Text = "保存失败：父目录不正确（不能将子级目录作为自身的父目录）。";
                        break;
                    default:
                        ltMsg.Text = "保存失败：未知错误。";
                        break;
                }
            }
        }

        // 批量添加子目录
        protected void btnBatchAdd_Click(object sender, EventArgs e)
        {
            Directory.Model.CategoryInfo.ErrorCode errorCode;
            int parentId = CascadingCategory_batch.SelectedId;

            string namestr = tbNameBat.Text;
            string[] name = namestr.Trim().Split(new char[] { '\n' });
            string err = string.Empty;
            foreach (string str in name)
            {
                Directory.Model.CategoryInfo cat = null;
                try
                {
                    cat = CategoryDataProxy.CreateCategory(str, CascadingCategory_batch.SelectedId, str, string.Empty, -1, out errorCode);
                }
                catch (Exception ex)
                {
                    err += ex.Message;
                }
            }
            ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('添加完成');Go2Category(" + parentId + ",false);</script>");
        }

        // 删除目录
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int categoryId;
            if (int.TryParse(Request[categoryIdKey], out categoryId))
            {
                Directory.Model.CategoryInfo cat = CategoryDataProxy.GetCategory(categoryId);
                if (cat == null)
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>location.replace(location.href);</script>");
                }
                try
                {
                    if (CategoryDataProxy.DeleteCategory(categoryId))
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('删除成功。');Go2Category(" + cat.ParentCategoryId + ",true);</script>");
                    }
                    else
                    {
                        ltMsg.Text = "删除失败：请确认该目录为空（没有子目录或条目）。";
                    }
                }
                catch
                {
                    ltMsg.Text = "删除失败：服务器错误。";
                }
            }
        }

    }
}